'use strict';


const Controller = require('egg').Controller;

class CustomizeController extends Controller {

  async toAlert(ctx) {
    if (!ctx.user) {
      ctx.redirect('/signin?redirect_url=/alert');
      return;
    }

    const user_id = ctx.user.id;
    const result = await ctx.service.alertSvc.listAlerts(user_id);
    result.pageTitle = '我的快讯';

    return await this.ctx.renderX('user/alert.nj', result);
  }

  async previewAlerts(ctx) {
    const kw = ctx.val('kw');
    const topics = await ctx.service.topicSvc.getDeliveryTopics(kw);

    topics.forEach(v => {
      v.author_name = v.author_name + '&nbsp;&nbsp;&nbsp;&nbsp;' + ctx.helper.ago(v.createdAt);
      if (!v.intro) {
        v.intro = '';
      }
      if (!v.original_url) {
        v.original_url = `https://taosha.club/topic/${v.id}`;
      }
    })

    return ctx.ok(topics);
  }

  async upsertAlert(ctx) {
    const kw = ctx.val('kw');
    const user_id = ctx.user.id;
    const result = await ctx.service.alertSvc.upsertAlert(user_id, kw);
    return ctx.ok();
  }

  async deleteAlert(ctx) {
    const kw = ctx.val('kw');
    const user_id = ctx.user.id;
    const result = await ctx.service.alertSvc.deleteAlert(user_id, kw);
    return ctx.ok(result);
  }

  async updateDeliveryHours(ctx) {
    const delivery_hours = ctx.val('delivery_hours');
    const user_id = ctx.user.id;
    const result = await ctx.service.alertSvc.updateDeliveryHours(user_id, delivery_hours);
    return ctx.ok(result);
  }


}

module.exports = CustomizeController;
